{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f0f03d96",
   "metadata": {},
   "source": [
    "##  优化百度ASR接口"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "85c748ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c20ef4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 以下为asr代码的优化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "7c425b80",
   "metadata": {},
   "outputs": [],
   "source": [
    "# zhichao : asr\n",
    "API_KEY = '",
    "SECRET_KEY = '"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "43f177fd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.e745b147b5112e7e4f94de384754fa5f.2592000.1655292652.282335-19331335'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 给使用者使用\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "xu_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5bc7693",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 准备音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "2159b609",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'好，北京科技馆。'"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = eval(asr(token = xu_token, AUDIO_FILE = '1.wav'))['result'][0]\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d320383",
   "metadata": {},
   "source": [
    "## 图灵机器人API测试\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "19508f46",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests,json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "55e974ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "TL_key = '你的KEY'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "08726265",
   "metadata": {},
   "outputs": [],
   "source": [
    "def TL_API(TL_key,text):\n",
    "    TL_url = 'http://openapi.turingapi.com/openapi/api/v2'\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_key,\n",
    "            \"userId\": \"0000001\"\n",
    "        }\n",
    "    }\n",
    "    payload_json = json.dumps(payload)\n",
    "    res = requests.post(TL_url,data=json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "d126c667",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "b3dd26c6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'广州:周一 05月16日,阴转多云 东北风转持续无风向,最低气温15度，最高气温22度。'"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f88c0a5",
   "metadata": {},
   "source": [
    "\n",
    "## 有图灵接口的语音识别对话机器人\n",
    "* 目标：我说一句话，电脑回复我文本信息(TULING_API)\n",
    "> 1. 准备音频（临时文件-时间期限）---音频文件\n",
    "> 2. 调用百度语音识别---文本信息（识别到的内容）\n",
    "> 3. 调用图灵机器人---文本信息（智能返回的内容）\n",
    "\n",
    "> 4. (待做).文本信息--> 语音合成 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "61580cec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2022%E5%B9%B405%E6%9C%8816%E6%97%A5%2CMon\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.1fff4ee0720f42d0b11d365fbad4c933.2592000.1655299159.282335-19331335&tex=2022%25E5%25B9%25B405%25E6%259C%258816%25E6%2597%25A5%252CMon&per=1&spd=7&pit=8&vol=5&aue=6&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.wav\n"
     ]
    }
   ],
   "source": [
    "# 1. 准备音频文件\n",
    "import speech_recognition\n",
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "\n",
    "# 2. 调用百度\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result = eval(asr(token = xu_token, AUDIO_FILE = '1.wav'))['result'][0]\n",
    "\n",
    "# 3. 调用图灵机器\n",
    "TL_API(TL_key,asr_result)\n",
    "\n",
    "# 4. 语音合成\n",
    "tts(xu_token,TL_API(TL_key,asr_result))\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dbdf61a8",
   "metadata": {},
   "source": [
    "## 语音识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "2ba05775",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "TEXT = \"欢迎使用百度语音合成。\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 1\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 7\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 8\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 6\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "def tts(token,text):\n",
    "    tex = quote_plus(text)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "50903059",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting pydub\n",
      "  Downloading pydub-0.25.1-py2.py3-none-any.whl (32 kB)\n",
      "Installing collected packages: pydub\n",
      "Successfully installed pydub-0.25.1\n",
      "\u001b[33mWARNING: You are using pip version 22.0.4; however, version 22.1 is available.\n",
      "You should consider upgrading via the '/Users/xuzhichao/anaconda3/bin/python -m pip install --upgrade pip' command.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "!pip install pydub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "16756d0c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/xuzhichao/anaconda3/lib/python3.7/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work\n",
      "  warn(\"Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work\", RuntimeWarning)\n"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c846c156",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
